package com.trace.demo.controller;

import com.trace.demo.entity.Farmer;
import com.trace.demo.entity.User;
import com.trace.demo.repository.FarmerRepository;
import com.trace.demo.repository.UserRepository;
import com.trace.demo.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/farmers")
public class FarmerController {

    @Autowired
    private FarmerRepository farmerRepository;

    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public ResponseEntity<ApiResponse<List<Farmer>>> getAllFarmers() {
        List<Farmer> farmers = farmerRepository.findAll();
        return ResponseEntity.ok(new ApiResponse<>(true, "Farmers retrieved successfully", farmers));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Farmer>> getFarmerById(@PathVariable Long id) {
        Optional<Farmer> farmer = farmerRepository.findById(id);
        return farmer.map(value -> ResponseEntity.ok(new ApiResponse<>(true, "Farmer retrieved successfully", value)))
                .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "Farmer not found with id: " + id, null)));
    }

    @PostMapping
    public ResponseEntity<ApiResponse<Farmer>> addFarmer(@RequestBody Farmer farmer, @RequestParam Long userId) {
        Optional<User> userOptional = userRepository.findById(userId);
        if (!userOptional.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "User not found with id: " + userId, null));
        }

        farmer.setUser(userOptional.get());
        Farmer savedFarmer = farmerRepository.save(farmer);
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(new ApiResponse<>(true, "Farmer added successfully", savedFarmer));
    }

    @PutMapping
    public ResponseEntity<ApiResponse<Farmer>> updateFarmer(@RequestBody Farmer farmer) {
        Optional<Farmer> existingFarmer = farmerRepository.findById(farmer.getId());
        if (!existingFarmer.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "Farmer not found with id: " + farmer.getId(), null));
        }

        farmer.setCreatedAt(existingFarmer.get().getCreatedAt());
        if (existingFarmer.get().getUser() != null) {
            farmer.setUser(existingFarmer.get().getUser());
        }

        Farmer updatedFarmer = farmerRepository.save(farmer);
        return ResponseEntity.ok(new ApiResponse<>(true, "Farmer updated successfully", updatedFarmer));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteFarmer(@PathVariable Long id) {
        Optional<Farmer> farmer = farmerRepository.findById(id);
        if (!farmer.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "Farmer not found with id: " + id, null));
        }

        farmerRepository.deleteById(id);
        return ResponseEntity.ok(new ApiResponse<>(true, "Farmer deleted successfully", null));
    }

    @GetMapping("/count")
    public ResponseEntity<ApiResponse<Long>> countFarmers() {
        Long count = farmerRepository.countFarmers();
        return ResponseEntity.ok(new ApiResponse<>(true, "Farmers count retrieved successfully", count));
    }

    @GetMapping("/count/today")
    public ResponseEntity<ApiResponse<Long>> countTodayNewFarmers() {
        LocalDateTime startOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT);
        Long count = farmerRepository.countTodayNewFarmers(startOfDay);
        return ResponseEntity.ok(new ApiResponse<>(true, "Today's new farmers count retrieved successfully", count));
    }

    @GetMapping("/count/province")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> countFarmersByProvince() {
        List<Map<String, Object>> distribution = farmerRepository.countFarmersByProvince();
        return ResponseEntity.ok(new ApiResponse<>(true, "Farmers by province count retrieved successfully", distribution));
    }

    @PutMapping("/{id}/verification-status")
    public ResponseEntity<ApiResponse<Farmer>> updateVerificationStatus(
            @PathVariable Long id,
            @RequestParam Farmer.VerificationStatus status,
            @RequestParam(required = false) String remark) {

        Optional<Farmer> existingFarmer = farmerRepository.findById(id);
        if (!existingFarmer.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "Farmer not found with id: " + id, null));
        }

        Farmer farmer = existingFarmer.get();
        farmer.setVerificationStatus(status);
        farmer.setVerificationRemark(remark);

        Farmer updatedFarmer = farmerRepository.save(farmer);
        return ResponseEntity.ok(new ApiResponse<>(true, "Farmer verification status updated successfully", updatedFarmer));
    }
}
